import { getWsClient } from "@/getClient";
import { useClientStore } from "@/pinia/stores/client";
import router from "@/route";
import { MsgConnectFailed } from "@/shared/protocols/AMessages/Test/MsgConnectFailed";
import { RTCConnection } from "@/utils/RTCConnection";
import { storeToRefs } from "pinia";
import { Ref, ref, watch, onMounted, onUnmounted } from "vue";

export function testhooks(testId: string) {
  const wsClient = getWsClient();
  const { currentUser } = storeToRefs(useClientStore());

  let screenStream: MediaStream | undefined;
  let rtcConnection: RTCConnection;
  let afterConnection: RTCConnection;

  wsClient.listenMsg(/^AMessages\/Test\//, (call, msgName) => {
    if (msgName === "AMessages/Test/ConnectFailed") {
      //考试不存在
      ElMessage.warning((call as MsgConnectFailed).message);
    }
  });
  //教师状态 决定rtc开启和关闭
  const teacherStatus: Ref<"online" | "offline"> = ref("offline");
  watch(teacherStatus, async (newValue) => {
    console.log(newValue);
    //rtc controller
    if (newValue === "online") {
      rtcConnection = new RTCConnection(
        wsClient,
        currentUser.value._id,
        "test",
        testId
      );
      if (screenStream === undefined) return;
      else {
        // screenStream.getTracks().forEach(track => {
        //     rtcConnection.videoProvider =  rtcConnection.peerConnection.addTrack(track,screenStream as MediaStream)
        // });
        const videoTracks = screenStream.getVideoTracks();
        if (videoTracks.length === 0) return;
        videoTracks[0].removeEventListener('ended',stopStream)
        videoTracks[0].addEventListener('ended',stopStream)
        rtcConnection.videoProvider = rtcConnection.peerConnection.addTrack(
          videoTracks[0],
          screenStream
        );
      }
      console.log("add stream");
    } else {
      rtcConnection.closeConnection();
    }
  });
  wsClient.listenMsg("AMessages/Test/TeacherStatus", async (call) => {
    try {
      if (screenStream === undefined) {
        screenStream = await navigator.mediaDevices.getDisplayMedia({
          // video:{
          //     width: 320,
          //     height: 180,
          //     // width:1280,
          //     // height:720
          // },
          // video: true,
          video: { 
            width: {ideal:1920,},
            height: {ideal:1080,},
            aspectRatio:16 / 9
          },
          audio: false,
        });
        // (videoRef.value as HTMLVideoElement).srcObject = screenStream
      }
    } catch (error) {
      if (error instanceof Error) {
        console.log(error.name); //NotAllowedError
        //未允许使用 跳回
        router.back();
      }
    }
    if (call.status === "connected") {
      //rtc connect
      console.log("rtc connect");
      teacherStatus.value = "online";
    } else {
      //rtc disconnect
      console.log("rtc disconnect");
      teacherStatus.value = "offline";
    }
  });
  //监听握手msg
  wsClient.listenMsg("AMessages/RTC/RTCConn", (msg) => {
    if (msg.type === "video-answer") rtcConnection.handleVideoAnswer(msg);
    else if (msg.type === "new-ice-candidate") {
      rtcConnection.addCandidate(msg);
      // if(msg.origin === rtcConnection.target){
      //     console.log('和前节点沟通');
      //     rtcConnection.addCandidate(msg);
      // }
      // else{
      //     console.log('和后节点沟通');
      //     afterConnection.addCandidate(msg)
      // }
    }
    // else if(msg.type === 'video-offer'){
    //     console.log("正在被当做节点");
    //     afterConnection = new RTCConnection(wsClient,currentUser.value._id)
    //     afterConnection.handleVideoOffer(msg)
    // }
  });
  wsClient.listenMsg("AMessages/RTC/SendTarget", (msg) => {
    rtcConnection.target = msg.target;
  });
  wsClient.listenMsg("AMessages/RTC/TestConn", async (msg) => {
    console.log(msg);
    if (msg.type === "fullscreen") {
      // const newStream = await navigator.mediaDevices.getDisplayMedia({
      //     video:{
      //         width: 1280,
      //         height: 720,
      //         // displaySurface: 'window'
      //     },
      //     audio:false
      // })
      // const newVideoTracks = newStream.getVideoTracks()
      // if(newVideoTracks.length === 0) return
      // rtcConnection.videoProvider?.replaceTrack(newVideoTracks[0]).then(res =>{
      //     console.log("fullscreen");
      // },err =>{
      //     console.log(err);
      // })
      if (!screenStream) return;
      const vidoeTracks = screenStream.getVideoTracks();
      if (!vidoeTracks) return;
      if (vidoeTracks.length !== 0) {
        vidoeTracks[0]
          .applyConstraints({
            width: { min: 640, ideal: 1280 },
            height: { min: 480, ideal: 720 },
            advanced: [
              { width: 1920, height: 1280 },
              // {aspectRatio: 1.333}
            ],
            // width:{ideal:1280},
            // height:{ideal:720}
          })
          .then(
            (res) => {
              console.log(vidoeTracks[0].getConstraints());
              rtcConnection = new RTCConnection(
                wsClient,
                currentUser.value._id,
                "test",
                testId
              );
              rtcConnection.videoProvider =
                rtcConnection.peerConnection.addTrack(
                  vidoeTracks[0],
                  screenStream as MediaStream
                );
            },
            (reject) => {
              console.log(reject);
            }
          );
      }
    }
  });

  const stopStream = () =>{
    console.log("stream stoped");
    ElMessage.warning('已停止共享，请重新进入页面')
  }

  onMounted(async () => {
    const v = await wsClient.connect();
    if (!v.isSucc) {
      ElMessage.error(v.errMsg);
      return 0;
    }

    await wsClient.sendMsg("AMessages/Test/JoinTest", {
      testId: testId,
      student: currentUser.value._id,
    });

    // mitt.on('trackReady',(value)=>{
    //     console.log('向前传递流');
    //     rtcConnection.streams.forEach(stream =>{
    //         stream.getTracks().forEach(track =>{
    //             rtcConnection.peerConnection.addTrack(track,stream,...afterConnection.streams)
    //         })
    //     })
    // })
  });
  onUnmounted(() => {
    console.log("asdf");
    wsClient.disconnect();
    // wsClient.unlistenMsg(/^AMessages\/Test\//, () => { })
    //清空rtc
    //关闭流（displayMedia）
    if(rtcConnection) rtcConnection.closeConnection();
    if (screenStream)
      screenStream.getTracks().forEach((track) => {
        track.stop();
      });
    screenStream = undefined;

    // mitt.off('trackReady')
  });

  return {
    wsClient
  };
}
